<?php

namespace App\Utils;

use App\Models\MProduct;
use Session;

/**
 * 购物车对象
 */
class ShoppingCar
{
    private static $SHOPPING_CAR = "SESSION_SHOPPING_CART";
    public $cart = array();

    /**
     * 在构造方法当中把已添加的商品解析出来
     */
    public function __construct()
    {
        if (SSUtil::has(self::$SHOPPING_CAR)) {
            $this->cart = unserialize(ss(self::$SHOPPING_CAR));
        }
    }

    /**
     * 添加（累计）商品到购物车
     */
    public function add($no, $num)
    {
        if ($num == 0) {
            return $this->del($no);
        } else {
            $hasBuyNum = empty($this->cart[$no]) ? 0 : $this->cart[$no];
            $this->cart[$no] = $num + $hasBuyNum;
            ss([self::$SHOPPING_CAR => serialize($this->cart)]);
            if (array_key_exists($no, $this->cart)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 删除购物车的商品
     */
    public function del($no)
    {
        unset($this->cart[$no]);
        ss([self::$SHOPPING_CAR => serialize($this->cart)]);
        if (!array_key_exists($no, $this->cart)) {
            return true;
        }
        return false;
    }

    /**
     * 销毁购物车
     */
    public function destroy()
    {
        SSUtil::forget(self::$SHOPPING_CAR);
    }

    /**
     * 获取所有的商品编号
     */
    public function no()
    {
        return array_keys($this->cart);
    }

    /**
     * 计算商品总价
     */
    public function calc()
    {
        $total = 0.00;
        $products = MProduct::whereIn('no', $this->no())->get();
        foreach ($products as $pro) {
            $total += $pro->p1 * $this->cart[$pro->no];
        }
        return $total;
    }

    /**
     * 返回拼接的购物车详情
     */
    public function detail()
    {
        $result = "";
        $allPro = MProduct::whereIn("no", $this->no())->get();
        foreach ($allPro as $pro) {
            $result .= $pro->title . "*" . $this->cart[$pro->no] . "  ";
        }
        return $result;
    }

}